/**
 * Copyright &copy; 2016-2022 liuhangjun All rights reserved.
 */
package com.magic.zhixin.service.impl;


import com.magic.zhixin.config.Constant;
import com.magic.zhixin.entity.UserInfo;
import com.magic.zhixin.repository.UserInfoRepository;
import com.magic.zhixin.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


/**
 * 用户信息Service
 * @author liuhangjun
 * @version 2017-06-15
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    public static final String PORTAL_CACHE_PREFIX = Constant.CACHE_PREFIX;

    @Autowired
    private UserInfoRepository userInfoRepository;


    private static final String MSG_CONTENT = "{verificationCode}";

    /**
     *
     * @param userId
     * @return
     */
    @Cacheable(value =  PORTAL_CACHE_PREFIX + "userInfo", key = "#root.target.PORTAL_CACHE_PREFIX + 'userInfo:id:' + #userId", unless = "#result == null")
    public UserInfo findOne(Long userId){

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);

        UserInfo userInfoResult = userInfoRepository.findByIdIs(userId);

        if (userInfoResult == null){
            return null;
        }

       return userInfoResult;

    }






    /**
     * 第三方用户登录处理逻辑
     * 先根据第三方的id判断数据库中是否有此用户，
     * 如果有那么直接返回用户信息，
     * 如果没有，那么插入一条用户信息到表中，然后返回此用户信息
     *
     * @param userInfo
     * @return
     */
    @Transactional
    public UserInfo thirdLogin(@NotNull UserInfo userInfo){
        UserInfo retUserInfo;

        //首先查询是否有此用户
        retUserInfo = userInfoRepository.findByOpenId(userInfo.getOpenId());

        if (retUserInfo == null){

            //新用户插入用户表
            retUserInfo= userInfoRepository.save(userInfo);

        }



        return retUserInfo;
    }


}
